<script setup lang="ts">
import {ref, watch, nextTick} from "vue";
import {Toast, TreeSelect} from "vant";
import {register} from "@/api/loginAndRegister";
import router from "@/router";

// 树形选择数据
const items = [
  {
    text: '专业',
    children: [
      {text: 'java', id: 1},
      {text: 'c++', id: 2},
      {text: 'go', id: 3},
      {text: '嵌入式', id: 4},
      {text: 'python', id: 5}
    ],
  },
  {
    text: '年级',
    children: [
      {text: '大一', id: 6},
      {text: '大二', id: 7},
      {text: '大三', id: 8},
      {text: '大四', id: 9},
      {text: '研一', id: 10},
      {text: '研二', id: 11},
      {text: '研三', id: 12},
    ],
  },
  {
    text: '性别',
    children: [
      {text: '男', id: 13},
      {text: '女', id: 14}
    ],
  },
  {
    text: '状态',
    children: [
      {text: '单身', id: 15},
      {text: '有对象', id: 16},
      {text: '已婚', id: 17},
      {text: 'emo', id: 18},
      {text: '内卷', id: 19}
    ],
  }
];

// 响应式数据
const activeIds = ref<number[]>([]); // 当前选中的ID数组
const activeIndex = ref(0); // 左侧导航索引
const selectedTags = ref<{ id: number, text: string }[]>([]); // 存储已选标签的文本和ID
const value = ref(''); // 搜索框值

// 搜索功能
const onSearch = (val: string) => {
  if (!val.trim()) return;

  // 遍历所有项目查找匹配项
  for (let i = 0; i < items.length; i++) {
    const group = items[i];
    const foundItem = group.children?.find(item => item.text.includes(val));
    if (foundItem) {
      // 跳转到对应分组并展开
      activeIndex.value = i;
      // 滚动到对应选项
      scrollToItem(foundItem.id);
      break;
    }
  }
};

// 滚动到指定选项
const scrollToItem = (id: number) => {
  nextTick(() => {
    const itemEl = document.querySelector(`[data-id="${id}"]`);
    if (itemEl) {
      itemEl.scrollIntoView({behavior: 'smooth', block: 'center'});
      // 高亮显示但不选中
      itemEl.classList.add('highlight');
      setTimeout(() => itemEl.classList.remove('highlight'), 2000);
    }
  });
};

const onCancel = () => {
  value.value = '';
  Toast('取消');
};

// 监听 activeIds 变化，更新 selectedTags
watch(activeIds, (newIds) => {
  selectedTags.value = [];
  newIds.forEach(id => {
    for (const group of items) {
      const found = group.children?.find(item => item.id === id);
      if (found) {
        selectedTags.value.push({id, text: found.text});
        break;
      }
    }
  });
}, {immediate: true});

// 删除标签
const removeTag = (id: number) => {
  activeIds.value = activeIds.value.filter(itemId => itemId !== id);
};

//注册方法
const doRegister = async () => {
  if (selectedTags.value.length === 0) {
    Toast.fail("请至少选择一个标签");
    return;
  }
  const {username, password, checkPassword, nickname, longitude, latitude} = history.state?.registerData;

  const tags = selectedTags.value.map(item => item.text);
  try {
    Toast("加载中 ...");
    const id = await register(username, password, checkPassword, nickname, longitude, latitude, tags);
    console.log("1");
  } catch (e) {
    Toast(e);
    console.log("e:", e);
    if ('账号已存在' == e) {
      await router.push('/user/register');
      return;
    }
  }

  await router.push('/user/login');
}
</script>

<template>
  <van-nav-bar title="请至少选择一个标签" left-arrow @click-left="router.push('/user/register')">
  </van-nav-bar>

  <form action="/">
    <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="selectedTags.length === 0" style="padding: 10px; color: #969799;">
    请选择标签
  </div>
  <div v-else style="padding: 8px;">
    <van-tag
        v-for="tag in selectedTags"
        :key="tag.id"
        closeable
        size="medium"
        type="primary"
        style="margin-right: 8px; margin-bottom: 8px;"
        @close="removeTag(tag.id)"
    >
      {{ tag.text }}
    </van-tag>
  </div>

  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="items"
  />

  <van-button type="primary" style="width: 94%; margin: 16px 3%;border-radius: 6px" @click="doRegister()">
    注册
  </van-button>
</template>

<style scoped>

</style>
